//
//  JJNetworkTools.swift
//  JJSina
//
//  Created by mac on 2017/12/5.
//  Copyright © 2017年 xinyuan. All rights reserved.
//

import UIKit
import AFNetworking

enum JJNetworkToolsMethod: String {
    case get = "get"
    case post = "post"
}
class JJNetworkTools: AFHTTPSessionManager {

    static let shared: JJNetworkTools = {
        let tools = JJNetworkTools()
    
//        tools.requestSerializer = AFJSONRequestSerializer()
//        tools.responseSerializer = AFJSONResponseSerializer()

        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()

    /// 网络请求公共方法
    ///
    /// - Parameters:
    ///   - method: 请求方式
    ///   - urlString: 请求url
    ///   - parameters: 请求参数
    ///   - success: 成功回调
    ///   - failure: 失败回调
    func request(method: JJNetworkToolsMethod, urlString: String, params: Any?, success: @escaping (Any?)->(), failure: @escaping (Error)->()) {
        if method == .get {
            self.get(urlString, parameters: params, progress: nil, success: { (_, res) in
                success(res)
            }, failure: { (_, err) in
                failure(err)
            })
        } else {
            self.post(urlString, parameters: params, progress: nil, success: { (_, res) in
                success(res)
            }, failure: { (_, err) in
                failure(err)
            })
        }
    }
    
    
}

extension JJNetworkTools {
    //MARK: - 获取accessTOKEN的方法
    func loadUserAccount(code: String, success: @escaping (Any?)->(), failure: @escaping (Error)->()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = [
            "client_id": JJ_APP_KEY,
            "client_secret": JJ_APP_SECRECT,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": JJ_REDIRECT_URI]
        request(method: JJNetworkToolsMethod.post, urlString: urlString, params: params, success: success, failure: failure)
    }
    //MARK: - 获取用户信息
    func loadUserInfo(userAccountModel: JJUserAccountModel, success: @escaping (Any?)->(), failure: @escaping (Error)->()) {
        let urlString = "https://api.weibo.com/2/users/show.json"
        let params = [
            "access_token": userAccountModel.access_token!,
            "uid": userAccountModel.uid!]
        request(method: JJNetworkToolsMethod.get, urlString: urlString, params: params, success: success, failure: failure)
    }
    //MARK: - 获取用户数据
    func loadUserData(success: @escaping (Any?)->(), failure: @escaping (Error)->()) {
        let urlString: String = "https://api.weibo.com/2/statuses/home_timeline.json"
        let params = ["access_token": JJOAuthViewModel.shared.accessToken!]
        request(method: JJNetworkToolsMethod.get, urlString: urlString, params: params, success: success, failure: failure)
    }
}














